package org.lanyu.springainovel.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.entity.TaskNotification;
import org.lanyu.springainovel.common.mapper.TaskNotificationMapper;
import org.lanyu.springainovel.common.service.TaskNotificationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务通知服务实现类 - 合并了异步任务和通知功能
 */
@Slf4j
@Service
public class TaskNotificationServiceImpl extends ServiceImpl<TaskNotificationMapper, TaskNotification> 
        implements TaskNotificationService {

    @Override
    @Transactional
    public TaskNotification createTask(String taskId, Long userId, String taskType, String title, String content) {
        TaskNotification taskNotification = new TaskNotification(taskId, userId, taskType, title, content);
        save(taskNotification);
        log.info("创建任务通知: taskId={}, userId={}, taskType={}", taskId, userId, taskType);
        return taskNotification;
    }

    @Override
    @Transactional
    public TaskNotification createNotification(Long userId, String title, String content, String priority) {
        TaskNotification notification = new TaskNotification(userId, title, content, priority);
        save(notification);
        log.info("创建通知: userId={}, title={}", userId, title);
        return notification;
    }

    @Override
    @Transactional
    public boolean updateTaskProgress(String taskId, int progress, String statusMessage) {
        TaskNotification taskNotification = getByTaskId(taskId);
        if (taskNotification == null) {
            log.warn("任务不存在: taskId={}", taskId);
            return false;
        }

        taskNotification.updateProgress(progress, statusMessage);
        boolean result = updateById(taskNotification);
        if (result) {
            log.debug("更新任务进度: taskId={}, progress={}", taskId, progress);
        }
        return result;
    }

    @Override
    @Transactional
    public boolean updateTaskStatus(String taskId, String status, String message) {
        TaskNotification taskNotification = getByTaskId(taskId);
        if (taskNotification == null) {
            log.warn("任务不存在: taskId={}", taskId);
            return false;
        }

        taskNotification.setStatus(status);
        if (message != null) {
            taskNotification.setContent(message);
        }

        // 根据状态更新进度
        switch (status) {
            case "PENDING":
                taskNotification.setProgress(0);
                break;
            case "RUNNING":
                if (taskNotification.getProgress() == null || taskNotification.getProgress() == 0) {
                    taskNotification.setProgress(10);
                }
                break;
            case "COMPLETED":
                taskNotification.setProgress(100);
                taskNotification.setCompletedAt(LocalDateTime.now());
                break;
            case "FAILED":
            case "CANCELLED":
                taskNotification.setCompletedAt(LocalDateTime.now());
                break;
        }

        boolean result = updateById(taskNotification);
        if (result) {
            log.debug("更新任务状态: taskId={}, status={}", taskId, status);
        }
        return result;
    }

    @Override
    @Transactional
    public boolean completeTask(String taskId, String result) {
        TaskNotification taskNotification = getByTaskId(taskId);
        if (taskNotification == null) {
            log.warn("任务不存在: taskId={}", taskId);
            return false;
        }

        taskNotification.completeTask(result);
        boolean success = updateById(taskNotification);
        if (success) {
            log.info("任务完成: taskId={}", taskId);
        }
        return success;
    }

    @Override
    @Transactional
    public boolean failTask(String taskId, String errorMessage) {
        TaskNotification taskNotification = getByTaskId(taskId);
        if (taskNotification == null) {
            log.warn("任务不存在: taskId={}", taskId);
            return false;
        }

        taskNotification.markAsFailed(errorMessage);
        boolean success = updateById(taskNotification);
        if (success) {
            log.info("任务失败: taskId={}, error={}", taskId, errorMessage);
        }
        return success;
    }

    @Override
    @Transactional
    public boolean cancelTask(String taskId) {
        TaskNotification taskNotification = getByTaskId(taskId);
        if (taskNotification == null) {
            log.warn("任务不存在: taskId={}", taskId);
            return false;
        }

        taskNotification.markAsCancelled();
        boolean success = updateById(taskNotification);
        if (success) {
            log.info("任务取消: taskId={}", taskId);
        }
        return success;
    }

    @Override
    public int getUnreadCount(Long userId) {
        return baseMapper.countUnreadByUserId(userId);
    }

    @Override
    public int getUnreadTaskCount(Long userId) {
        return baseMapper.countUnreadTasksByUserId(userId);
    }

    @Override
    public List<TaskNotification> getAllByUserId(Long userId) {
        return baseMapper.findAllByUserId(userId);
    }

    @Override
    public List<TaskNotification> getUnreadByUserId(Long userId) {
        return baseMapper.findUnreadByUserId(userId);
    }

    @Override
    public List<TaskNotification> getActiveTasksByUserId(Long userId) {
        return baseMapper.findActiveTasksByUserId(userId);
    }

    @Override
    public List<TaskNotification> getCompletedTasksByUserId(Long userId) {
        return baseMapper.findCompletedTasksByUserId(userId);
    }

    @Override
    public TaskNotification getByTaskId(String taskId) {
        return baseMapper.findByTaskId(taskId);
    }

    @Override
    public List<TaskNotification> getActiveTasksByUserIdAndType(Long userId, String taskType) {
        return baseMapper.findActiveTasksByUserIdAndType(userId, taskType);
    }

    @Override
    @Transactional
    public boolean markAsRead(Long id) {
        int result = baseMapper.markAsRead(id);
        if (result > 0) {
            log.debug("标记通知为已读: id={}", id);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean markAllAsRead(Long userId) {
        int result = baseMapper.markAllAsReadByUserId(userId);
        if (result > 0) {
            log.info("标记用户所有通知为已读: userId={}, count={}", userId, result);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean deleteReadTasks(Long userId) {
        int result = baseMapper.deleteReadTasksByUserId(userId);
        if (result > 0) {
            log.info("删除用户已读任务: userId={}, count={}", userId, result);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean deleteReadNotifications(Long userId) {
        int result = baseMapper.deleteReadNotificationsByUserId(userId);
        if (result > 0) {
            log.info("删除用户已读通知: userId={}, count={}", userId, result);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean deleteOldCompletedTasks(Long userId, int days) {
        int result = baseMapper.deleteOldCompletedTasks(userId, days);
        if (result > 0) {
            log.info("删除用户旧已完成任务: userId={}, days={}, count={}", userId, days, result);
            return true;
        }
        return false;
    }

    @Override
    public TaskNotification getById(Long id) {
        return super.getById(id);
    }

    @Override
    @Transactional
    public boolean deleteById(Long id) {
        boolean result = super.removeById(id);
        if (result) {
            log.info("删除通知: id={}", id);
        }
        return result;
    }
}